package com.changgou.oauth2.controller;

import com.changgou.oauth2.pojo.AuthToken;
import com.changgou.oauth2.service.LoginServiceImpl;
import com.changgou.oauth2.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/login")
public class LoginController {
    //客户端ID
    @Value("${auth.clientId}")
    private String clientId;

    //秘钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    //Cookie存储的域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;
    //Redis的保存时间
    @Value("${auth.ttl}")
    private Long ttl;
    @Autowired
    private LoginServiceImpl loginService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping
    public String login(String ReturnUrl, Model model) {
        model.addAttribute("ReturnUrl", ReturnUrl);
        /*必须引入试图解析器依赖才可以跳转视图*/
        return "login";
    }

    @PostMapping
    public String login(String username, String password, String ReturnUrl) {
        AuthToken authToken = loginService.login(username, password,clientId,clientSecret);

        /*保存到cookie*/
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        CookieUtil.addCookie(servletRequestAttributes.getResponse(), cookieDomain, "/",
                "userKey", authToken.getJti(), cookieMaxAge, false);
        /*保存到Redis*/
        stringRedisTemplate.boundValueOps(authToken.getJti()).set(authToken.getAccessToken(), ttl, TimeUnit.SECONDS);

        return "redirect:" + ReturnUrl;
    }
}